<template>
  <div id="app4">
    <NavBar />
  <div class="timeline-container">
    <!-- 顶部标题和筛选区 -->
    <div class="timeline-header">
      <h1>抗日战争时间线</h1>
      <div class="filter-section">
        <el-radio-group v-model="timelineType" size="large">
          <el-radio-button label="all">全部类型</el-radio-button>
          <el-radio-button label="political">政治外交</el-radio-button>
          <el-radio-button label="military">军事行动</el-radio-button>
          <el-radio-button label="social">社会民生</el-radio-button>
          <el-radio-button label="international">国际关系</el-radio-button>
        </el-radio-group>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="timeline-main">
      <!-- 左侧年份导航 -->
      <div class="year-nav">
        <div class="year-list">
          <div 
            v-for="year in timelineYears" 
            :key="year"
            class="year-item"
            :class="{ active: currentYear === year }"
            @click="scrollToYear(year)"
          >
            {{ year }}
          </div>
        </div>
      </div>

      <!-- 中间事件展示区 -->
      <div class="events-section" ref="eventsContainer" @scroll="handleScroll">
        <div 
          v-for="year in yearGroups" 
          :key="year.year" 
          class="year-section"
          :id="`year-${year.year}`"
          ref="yearSections"
        >
          <div class="year-header">{{ year.year }}</div>
          <el-timeline>
            <el-timeline-item
              v-for="event in year.events"
              :key="event.id"
              :timestamp="event.date"
              :type="getTimelineItemType(event)"
            >
              <el-card :class="{ 'key-event': event.importance === 'key' }">
                <template #header>
                  <div class="event-header">
                    <h3>
                      <el-tag v-if="event.importance === 'key'" type="danger" effect="dark">关键事件</el-tag>
                      {{ event.title }}
                    </h3>
                    <div class="event-tags">
                      <el-tag :type="getTagType(event.type)">
                        {{ EVENT_TAGS[event.type].label }}
                      </el-tag>
                      <el-tag 
                        v-for="subType in event.subTypes" 
                        :key="subType"
                        :type="getTagType(subType)"
                        effect="plain"
                      >
                        {{ EVENT_TAGS[subType].label }}
                      </el-tag>
                    </div>
                  </div>
                </template>
                <div class="event-content">
                  <p>{{ event.description }}</p>
                  <div class="event-media" v-if="event.images && event.images.length">
                  </div>
                  <div class="event-significance" v-if="event.significance">
                    <el-collapse>
                      <el-collapse-item title="历史意义">
                        <div v-for="(value, key) in event.significance" :key="key">
                          <p><strong>{{ EVENT_TAGS[key]?.label || key }}：</strong>{{ value }}</p>
                        </div>
                      </el-collapse-item>
                    </el-collapse>
                  </div>
                </div>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>

      <!-- 右侧事件列表 -->
      <div class="events-nav">
        <div class="search-box">
          <el-input
            v-model="searchQuery"
            placeholder="搜索事件..."
            prefix-icon="Search"
          />
        </div>
        <div class="events-tree">
          <el-tree
            :data="eventTreeData"
            :props="defaultProps"
            @node-click="handleEventClick"
            :filter-node-method="filterNode"
            ref="eventTree"
          />
        </div>
      </div>
    </div>
  </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { events,  EVENT_TAGS } from '@/modules/module3/module3-kangri/data'
import NavBar from '@/modules/module3/module3-kangri/components/NavBar.vue'
// 状态管理
const searchQuery = ref('')
const timelineType = ref('all')
const currentYear = ref(null)
const eventsContainer = ref(null)
const eventTree = ref(null)
const yearSections = ref([])

// 计算属性：根据类型筛选事件
const filteredEvents = computed(() => {
  if (timelineType.value === 'all') return events
  return events.filter(event => 
    event.type === timelineType.value || 
    event.subTypes?.includes(timelineType.value)
  )
})

// 计算属性
const timelineYears = computed(() => {
  return [...new Set(filteredEvents.value.map(event => event.year))].sort()
})

const yearGroups = computed(() => {
  const groups = {}
  filteredEvents.value.forEach(event => {
    if (!groups[event.year]) {
      groups[event.year] = {
        year: event.year,
        events: []
      }
    }
    groups[event.year].events.push(event)
  })

  return Object.values(groups).sort((a, b) => a.year - b.year)
})

const eventTreeData = computed(() => {
  return yearGroups.value.map(yearGroup => ({
    label: yearGroup.year,
    children: yearGroup.events.map(event => ({
      label: `${event.importance === 'key' ? '★ ' : ''}${event.title}`,
      id: event.id
    }))
  }))
})

// 方法
const getTagType = (type) => {
  return EVENT_TAGS[type]?.type || 'info'
}

const getTimelineItemType = (event) => {
  return event.importance === 'key' ? 'danger' : 'primary'
}

const handleScroll = () => {
  if (!eventsContainer.value) return
  
  const containerRect = eventsContainer.value.getBoundingClientRect()
  const containerCenter = containerRect.top + containerRect.height / 2
  
  let closestSection = null
  let minDistance = Infinity
  
  yearSections.value.forEach(section => {
    if (!section) return
    const sectionRect = section.getBoundingClientRect()
    const sectionCenter = sectionRect.top + sectionRect.height / 2
    const distance = Math.abs(containerCenter - sectionCenter)
    
    if (distance < minDistance) {
      minDistance = distance
      closestSection = section
    }
  })
  
  if (closestSection) {
    currentYear.value = parseInt(closestSection.id.replace('year-', ''))
  }
}

const scrollToYear = (year) => {
  const element = document.getElementById(`year-${year}`)
  if (element) {
    element.scrollIntoView({ behavior: 'smooth', block: 'center' })
  }
}

const handleEventClick = (data) => {
  if (data.id) {
    const event = filteredEvents.value.find(e => e.id === data.id)
    if (event) {
      scrollToYear(event.year)
    }
  }
}

const filterNode = (value, data) => {
  if (!value) return true
  return data.label.toString().includes(value)
}

// 监听搜索词变化
watch(searchQuery, (val) => {
  eventTree.value?.filter(val)
})

// 生命周期钩子
onMounted(() => {
  if (timelineYears.value.length) {
    currentYear.value = timelineYears.value[0]
  }
})
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html, body {
  height: 100%;
  width: 100%;
  overflow-x: hidden;
  background-color: #f5f7fa;
}

#app4 {
  min-height: 100vh;
  width: 100%;
  min-height: 100vh;
  width: 100%;
  background-image: url('@/modules/module3/module3-kangri/assets/image/bg-global.jpg'); /* 替换为你的背景图片路径 */
  background-size: cover;
  background-position: center;
  background-attachment: fixed; /* 使背景固定，不随滚动移动 */
}
.timeline-container {
  height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
}

.timeline-header {
  padding: 20px;
  text-align: center;
}

.timeline-main {
  flex: 1;
  display: grid;
  grid-template-columns: 80px 1fr 300px;
  gap: 20px;
  padding: 20px;
  overflow: hidden;
}

.filter-section {
  margin-top: 20px;
}

/* 左侧年份导航 */
.year-nav {
  border-radius: 8px;
  overflow-y: auto;
  padding: 10px;
}

.year-item {
  padding: 10px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
}

.year-item.active {
  background: #409EFF;
  color: white;
  border-radius: 4px;
}

/* 中间事件展示区 */
.events-section {
  margin-left: 40px;
  background: white;
  border-radius: 8px;
  overflow-y: auto;
  padding: 20px;
}

.year-section {
  margin-bottom: 40px;
}

.year-header {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #409EFF;
}

.event-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.event-tags {
  display: flex;
  gap: 8px;
}

.event-content {
  padding: 10px 0;
}

.event-media {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 10px;
  margin: 10px 0;
}

.event-significance {
  margin-top: 10px;
}

/* 关键事件样式 */
.key-event {
  border: 2px solid #F56C6C;
  box-shadow: 0 2px 12px 0 rgba(245, 108, 108, 0.1);
}

.key-event .el-card__header {
  background-color: #FEF0F0;
}

/* 右侧事件列表 */
.events-nav {
  background: white;
  width: 75%;
  margin-left: 40px;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px;
}

.search-box {
  position: sticky;
  top: 0;
  background: white;
  z-index: 1;
}
</style>